<template>
  <div class="app-container">
    <div class="body-div">
      <div style="padding: 10px">
        <el-row style="margin-top: 8px">
          <el-col :span="20">
            <div style="display: flex; margin-top: 10px; width: 100%">
              <div class="shuxian"></div>
              <span class="headtitle">全部设计方案</span>
            </div>
          </el-col>
          <el-col :span="4">
            <el-button
              type="primary"
              style="float: right; margin-left: 10px"
              @click="back()"
              >返回</el-button
            >
            <el-button type="primary" style="float: right" @click="compare()"
              >方案比对</el-button
            >
          </el-col>
        </el-row>
        <div style="margin-top: 15px">
          <el-table
            :data="tableData"
            border
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="time"
              width="250"
              align="center"
              label="时间"
            />
            <el-table-column prop="name" align="center" label="方案名称" />
            <el-table-column prop="type" align="center" label="工况名称" />
            <el-table-column label="操作" align="center" width="180">
              <template #default="scope">
                <el-button
                  :icon="Search"
                  circle
                  style="margin-left: 10px"
                  @click="lookDetail(scope.row.id, scope.row.computeId)"
                />
                <el-button
                  :icon="Bottom"
                  type="primary"
                  circle
                  style="margin-left: 10px"
                  @click="download(scope.row.id, scope.row.computeId)"
                />
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  style="margin-left: 10px"
                  v-hasPermi="['project:projectData:removeDesign']"
                  @click="deleteDetail(scope.row.id, scope.row.name)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import request from "@/utils/request";
import { ElMessage, ElPopover, ElButton, ElMessageBox } from "element-plus";
import { Search, Delete, Bottom } from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
import axios from "axios";

const router = useRouter();
const route = useRoute();
const id = route.params.id;

const tableData = ref([]);
const selectTableData = ref([]);

function back() {
  router.push(`/projects/projectData/detail/${id}`).then(() => {});
}

function deleteDetail(itemId, itemName) {
  ElMessageBox.confirm(`是否确认删除设计方案：${itemName}？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: `/system/project/deleteMstnSchemeBatchByBatchId/${itemId}`,
        method: "get",
      }).then((response) => {
        if (response.code == 200) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.error("删除失败");
        }
      });
    })
    .catch(() => {});
}

function lookDetail(itemId, computeId) {
  router.push(
    `/projects/projectData/designDetailProject/${id}/${itemId}/${computeId}`
  );
}


function download(itemId, computeId) {
  return request({
    url: "/system/project/export/pdf",
    method: "POST",
    data: { batchId: itemId, projectId: id },
    responseType: "blob", // 重要：告诉axios接收二进制数据
  })
    .then((response) => {
      console.log("response:", response);
      // 后端返回的就是 PDF 二进制 Blob，直接使用即可
      const blob = new Blob([response], { type: "application/pdf" });
      const url = URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = url;
      // 文件名可从响应头获取（后端已设置），或自定义
      a.download = "document.pdf";
      a.click();

      // 释放资源
      URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error("下载失败:", error);
    });
}

//表格勾选
function handleSelectionChange(val) {
  selectTableData.value = val;
}

//方案比对
function compare() {
  console.log(selectTableData.value);
  if (selectTableData.value.length < 2) {
    ElMessage.error("请至少选择两个方案进行比对");
    return;
  }
  router.push({
    path: `/projects/projectData/designDetailProject/${id}/0/0`,
    query: {
      batchIdList: selectTableData.value.map((item) => item.id).join(","),
    },
  });
}

//年月日时分秒格式时间
function formatDateTime1(dateTimeStr) {
  const date = new Date(dateTimeStr);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function getList() {
  request({
    url: "/system/project/v2/selectDesignList/" + id,
    method: "get",
    params: {},
  }).then((response) => {
    if (response.code == 200 && response.data.length > 0) {
      tableData.value = response.data.map((item) => ({
        id: item[0],
        time: formatDateTime1(item[1]),
        name: item[2],
        type: item[3],
        computeId: item[4],
      }));
    }
  });
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.design-center {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.app-bottom {
  width: 100%;
  margin: auto;
  background-color: #f5f5f5;
  font-size: smaller;
  text-align: center;
  line-height: 50px;
}

.headtitle {
  margin-left: 10px;
  font-size: 18px;
}

.app-container {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.body-div {
  height: calc(100% - 20px);
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow-y: auto;
}

.shuxian {
  height: 23px;
  width: 5px;
  background-color: #355af0;
}

.form-title {
  font-size: 14px;
  font-weight: 400;
  color: #395df0;
}

.form-text {
  font-size: 14px;
  font-weight: 400;
  color: #727272;
}
</style>
